package com.wwj.auction.login.controller;


import com.alipay.api.AlipayApiException;
import com.wwj.auction.common.result.R;
import com.wwj.auction.login.config.AlipayTemplate;
import com.wwj.auction.login.config.PayVo;
import com.wwj.auction.login.entity.to.UserInfoTo;
import com.wwj.auction.login.service.TransFlowService;
import com.wwj.auction.login.service.UserAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wwj
 * @since 2021-08-10
 */
@RestController
@RequestMapping("/login/userAccount")
@Slf4j
@Api("用户账户")
public class UserAccountController {

    @Autowired
    private AlipayTemplate alipayTemplate;
    @Autowired
    private TransFlowService transFlowService;
    @Autowired
    private UserAccountService userAccountService;

    @ApiOperation("提交支付请求，跳转支付宝")
    @PostMapping("/auth/commitCharge/{type}/{userId}/{chargeAmt}")
    public R commitCharge(@PathVariable("type") Integer type,
                          @PathVariable("userId") Integer userId,
                          @PathVariable("chargeAmt") String chargeAmt,
                          HttpServletRequest request) throws AlipayApiException {
        UserInfoTo userInfoTo = new UserInfoTo();
        userInfoTo.setId(userId);
        userInfoTo.setType(type);
        userInfoTo.setAmounts(chargeAmt);
        // 将当前用户的交易信息存入ServletContext
        request.getServletContext().setAttribute("userInfoTo", userInfoTo);

        PayVo payVo = new PayVo();
        // 设置订单号
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        payVo.setOut_trade_no(uuid);
        payVo.setSubject("人人拍卖");
        payVo.setTotal_amount(chargeAmt);
        // 返回动态生成的表单，该表单可直接提交
        String payForm = alipayTemplate.pay(payVo);
        // 增加账户余额
        transFlowService.addAmount(userInfoTo);
        return R.ok().data("payForm", payForm);
    }

    @ApiOperation("支付宝异步回调接口")
    @PostMapping("/notify")
    public String notifyPay(HttpServletRequest request) {
        // 获取支付宝返回的参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        // 获取ServletContext中的交易信息
        UserInfoTo userInfoTo = (UserInfoTo) request.getServletContext().getAttribute("userInfoTo");
        transFlowService.savePay(parameterMap, userInfoTo);
        // 返回success后，支付宝将确认此次支付请求成功被商家收到
        return "success";
    }

    @ApiOperation("扣减账户余额")
    @GetMapping("/subtract/amount/{userId}/{shopPrice}/{earnestMoney}/{shopFreight}")
    public R subtractAmount(
            @PathVariable("userId") Integer userId,
            @PathVariable("shopPrice") BigDecimal shopPrice,
            @PathVariable("earnestMoney") BigDecimal earnestMoney,
            @PathVariable("shopFreight") BigDecimal shopFreight
    ) {
        userAccountService.subtractAmount(userId,shopPrice, earnestMoney, shopFreight);
        return R.ok();
    }
}

